//
//  UserAccountViewModel.swift
//  Practice
//
//  Created by miaozhihui on 2016/12/21.
//  Copyright © 2016年 DeKuTree. All rights reserved.
//

import Foundation


/// 用户账号 视图模型
class UserAccountViewModel {
    
    static let sharedUserAccount = UserAccountViewModel()
    
    /// 用户模型
    var account:UserAccount?
    
    /// 返回有效的token
    var accessToken: String? {
        // 如果没有过期，返回token
        if !isExpired {
            return account?.access_token
        }
        return nil
    }
    
    /// 用户登录标记
    var userLogin: Bool {
        // 如果token有值，说明登录成功
        // 如果没有过期，说明登录有效
        return account?.access_token != nil && !isExpired
    }
    
    /// 归档保存的路径
    fileprivate var accountPath:String {
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
        return (path as NSString).appendingPathComponent("account.plist")
    }
    
    /// 判断账户是否过期
    var isExpired: Bool {
        // 用户账户过期日期与当前系统日期进行比较
        if account?.expiresDate?.compare(Date()) == ComparisonResult.orderedDescending {
            return false
        }
        // 过期返回 true
        return true
    }
    /// 构造函数
    private init() {
        // 从沙盒解档数据
//        account = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as? UserAccount
        
        // 判断token是否过期
        if isExpired {
            print("已经过期")
            account = nil
        }
        print(account ?? "解档用户模型失败")
    }
}

// MARK: - 用户账户相关的网络方法
extension UserAccountViewModel {
    
    /// 加载token
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - finished: 完成回调
    func loadAccessToken(code:String,finished:@escaping (_ isSuccessed:Bool)->()) {
        NetworkTools.sharedTools.loadAccessToken(code: code) { (result, error) in
            if error != nil {
                print("出错了 \(error)")
                finished(false)
                return
            }
            NetworkTools.sharedTools.userAccount.yy_modelSet(withJSON: result ?? [:])
            self.loadUserInfo(account: NetworkTools.sharedTools.userAccount,finished: finished)
        }
    }
    
    /// 加载用户信息
    ///
    /// - Parameters:
    ///   - account: 用户账户对象
    ///   - finished: 完成回调
    private func loadUserInfo(account:UserAccount,finished:@escaping (_ isSuccessed:Bool)->()) {
        NetworkTools.sharedTools.loadUserInfo(uid: account.uid!) { (result, error) in
            if error != nil {
                print("加载用户信息出错了")
                finished(false)
                return
            }
            
            guard let dict = result as? [String:Any] else {
                print("格式错误")
                finished(false)
                return
            }
            print(account)
            // 保存用户信息
            account.yy_modelSet(with: dict)
//            account.screen_name = dict["screen_name"] as? String
//            account.avatar_large = dict["avatar_large"] as? String
            print(account)
            NetworkTools.sharedTools.userAccount.saveAccount()
            // 保存对象(归档)
//            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
            
            // 完成回调(必须调用)
            finished(true)
        }
    }
}
